var url = require('url');
var fs = require('fs');
var formidable = require('formidable');
var querystring = require('querystring');
var weiboApi = require('../lib/weiboApi');
var config = require('./config');

// weiboApi.init({
//   app_key: APP_KEY,
//   app_secret: APP_SECRET,
//   app_redirect_uri: APP_REDIRECT_URI
// });
weiboApi.init(config.weibo_app_info);

module.exports = {
  followers: function (req, res) {
    var query = url.parse(req.url, true).query;
    if (!query.uid) {
      json(res, {
        error: 'uid lost',
        data: null
      });
      return;
    }
    weiboApi.friendshipsFollowers({
      uid: query.uid,
      count: 10
    }, function (err, data) {
      // console.log('friendshipsFollowers', err, data);
      json(res, {
        error: err,
        data: data
      });
    });
  },


  statusesUpdate: function (req, res) {
    if (!isFormData(req)) {
      res.statusCode = 400;
      res.end('Bad Request: expecting multipart/form-data');
      return;
    }

    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
      // console.log('fields', fields);
      // console.log('files', files);
      if (!fields.content) {
        json(res, {
          error: 'content lost',
          data: null
        });
      }

      var file = files.pic;
      if (file.size > 0) {
        // upload img
        fs.readFile(file.path, function (err, data) {
          if (err) {
            json(res, {
              error: err,
              data: null
            });
          } else {
            var pic = {
              data: data,
              field: 'pic',
              name: file.name,
              type: file.type
            };
            // console.log('data', typeof data, Buffer.isBuffer(data), pic.name, file.type);
            weiboApi.statusesUpload({
              status: fields.content
            }, pic, function (err, result) {
              json(res, {
                error: err,
                data: result
              });
            });
          }
        });
      } else if (fields.pic_url) {
        // img url
        weiboApi.getWebImage(fields.pic_url, function (err, pic) {
          if (err) {
            json(res, {
              error: err,
              data: null
            });
          } else {
            // showFile(res, pic.type, pic.data);
            pic.field = 'pic';
            pic.name = 'weibo-pic';
            weiboApi.statusesUpload({
              status: fields.content
            }, pic, function (err, result) {
              json(res, {
                error: err,
                data: result
              });
            });
          }
        });
      } else {
        // text only
        weiboApi.statusesUpdate({
          status: fields.content
        }, function (err, data) {
          json(res, {
            error: err,
            data: data
          });
        });
      }
    });
  },


  statusesRepost: function (req, res) {
    var postData = '';

    req.addListener('data', function (chunk) {
      postData += chunk;
    });

    req.addListener('end', function () {
      postData = querystring.parse(postData);
      weiboApi.statusesRepost({
        id: postData.id,
        status: postData.status,
        is_comment: postData.is_comment
      }, function (err, data) {
        json(res, {
          error: err,
          data: data
        });
      });
    });
  },


  comments: function (req, res) {
    var query = url.parse(req.url, true).query;
    if (!query.id) {
      json(res, {
        error: 'id lost',
        data: null
      });
    } else {
      weiboApi.commentsShow({
        id: query.id,
        page: query.page || 1,
        count: query.count || 10
      }, function (err, data) {
        json(res, {
          error: err,
          data: data
        });
      });
    }
  },


  commentCreate: function (req, res) {
    var postData = '';

    req.addListener('data', function (chunk) {
      console.log('data', chunk);
      postData += chunk;
    });

    req.addListener('end', function () {
      postData = querystring.parse(postData);
      weiboApi.commentsCreate({
        id: postData.id,
        comment: postData.comment
      }, function (err, data) {
        json(res, {
          error: err,
          data: data
        });
      });
    });
  }
};


function isFormData (req) {
    var type = req.headers['content-type'] || '';
    return 0 == type.indexOf('multipart/form-data');
}


function json (res, obj) {
  res.writeHead(200, {
    'Content-Type': 'application/json; charset=utf-8'
  });
  res.write(JSON.stringify(obj));
  res.end();
}


function showFile (res, type, data) {
  res.writeHead(200, {
    'Content-Type': type
  });
  res.write(data, 'binary');
  res.end();
}
